package com.lyw.utils;

import com.lyw.domain.GlobalConfigurationInfo;
import com.lyw.enums.*;
import com.lyw.factory.TimerTaskFactory;
import org.bytedeco.javacv.JavaCV;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.awt.image.DataBufferByte;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.IntStream;

/**
 * 角色工具
 */
public class CharacterUtil {

  public static final int RANGE = 10;
  public static final int CHARACTER_RANGE = 50;

  private CharacterUtil() {
  }

  public static void switchCharacter(GlobalConfigurationInfo configInfo, Robot robot, Rectangle rectangle) throws Exception {

    Point location = rectangle.getLocation();
    String[] split = configInfo.getCharacterPageStartCoordinate().split("-");
    int x = (int) (Integer.parseInt(split[0]) + location.getX());
    int y = (int) (Integer.parseInt(split[1]) + location.getY());

    Long curRole = configInfo.getCurrentRoleIndex();

    // 结束
    if (curRole > configInfo.getCharacterCounts()) {
      System.out.println("刷完了.....................................");
    }

    if (curRole != 0) {

      long curIndex = curRole % configInfo.getCharacterCountEveryRow();
      x = (int) (x + (configInfo.getCharacterPageInterval() * curIndex));

      if (curRole % (configInfo.getCharacterCountEveryRow() * configInfo.getCurrentRoleRowIndex()) == 0) {
        String[] nextRowCharacters = configInfo.getNextRowOfCharacters().split("-");
        int nextRowX = (int) location.getX() + Integer.parseInt(nextRowCharacters[0]);
        int nextRowY = (int) location.getY() + Integer.parseInt(nextRowCharacters[1]);
        robot.mouseMove(nextRowX, nextRowY);
        int i = RandomUtil.RANDOM.nextInt(100);
        robot.delay(300 + i);
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        robot.delay(80);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

        configInfo.setCurrentRoleRowIndex(configInfo.getCurrentRoleRowIndex() + 1);
        GlobalConfigUtil.editSimplePropertiesFileValue("currentRoleRowIndex", configInfo.getCurrentRoleRowIndex().toString());
      }
    }

    // 鼠标移动
    robot.mouseMove(x, y);

    // 如果颜色不是指定颜色，不是可刷图角色
    Color roleColor = robot.getPixelColor(x, y);
    if (!matchCharacter(roleColor, configInfo)) {
      robot.delay(2000);
      System.out.println("当前角色不是能刷图的角色！");
      configInfo.setCurrentRoleIndex(configInfo.getCurrentRoleIndex() + 1);
      switchCharacter(configInfo, robot, rectangle);
      return;
    }

    robot.delay(2000);
    MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);
    MouseAndKeyEventUtil.keyEnter(KeyEvent.VK_SPACE);
    robot.delay(2000);

    // 判断是否刷完
    String[] triedCoordinate = configInfo.getTriedCoordinate().split("-");
    int triedX = ((int) location.getX()) + Integer.parseInt(triedCoordinate[0]);
    int triedY = ((int) location.getY()) + Integer.parseInt(triedCoordinate[1]);
    robot.mouseMove(triedX, triedY);
    Color triedColor = robot.getPixelColor(triedX, triedY);

    System.out.println(StringUtil.format("rgb({}, {}, {})", triedColor.getRed(), triedColor.getGreen(), triedColor.getBlue()));
    String[] triedColors = configInfo.getTriedColor().split("-");

    if (Integer.parseInt(triedColors[0]) != triedColor.getRed()
            && Integer.parseInt(triedColors[1]) != triedColor.getGreen()
            && Integer.parseInt(triedColors[2]) != triedColor.getBlue()) {
//        if (true) {

      robot.delay(200);
      MouseAndKeyEventUtil.keyEnter(KeyEvent.VK_ESCAPE);

      robot.delay(1000);
      String[] switchCharacter = configInfo.getSwitchCharacter().split("-");
      robot.mouseMove((int) location.getX() + Integer.parseInt(switchCharacter[0]), (int) location.getY() + Integer.parseInt(switchCharacter[1]));

      MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);

      robot.delay(3000);
      configInfo.setCurrentRoleIndex(curRole + 1);
      // 切换角色
      switchCharacter(configInfo, robot, rectangle);
    }

    // 数据记录
    // 切换角色信息
    configInfo.setCurrentRoleIndex(curRole + 1);
    GlobalConfigUtil.editSimplePropertiesFileValue("currentRoleIndex", configInfo.getCurrentRoleIndex().toString());
  }

  /**
   * 从西海岸进入对应的地图，然后通过大地图走到副本门口
   */
  public static void clickMap(Robot robot, Point location, MapPosition mapPosition, int keyboardDirection) throws Exception {

    String[] split = mapPosition.getPosition().split("-");
    MouseAndKeyEventUtil.move(split, location);
    robot.delay(200);
    MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);
    robot.delay(300);
    MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);
    robot.delay(1000);
    MouseAndKeyEventUtil.keyEnter(KeyEvent.VK_N);

    String[] duplicatePosition = mapPosition.getDuplicatePosition().split("-");
    int[] duplicate = {(int) (Integer.parseInt(duplicatePosition[0]) + location.getX()),
            (int) (Integer.parseInt(duplicatePosition[1]) + location.getY())};

    MouseAndKeyEventUtil.move(duplicate);
    MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);
    String[] smallCharacterIcon = ColorCodeLibraryEnum.SMALL_MAP_CHARACTER.getColor().split("-");

    while (true) {
      Color pixelColor = robot.getPixelColor(duplicate[0], duplicate[1]);
      if (Integer.parseInt(smallCharacterIcon[0]) == pixelColor.getRed()
              && Integer.parseInt(smallCharacterIcon[1]) == pixelColor.getGreen()
              && Integer.parseInt(smallCharacterIcon[2]) == pixelColor.getBlue()) {
        break;
      }
    }
    robot.delay(900 + RandomUtil.RANDOM.nextInt(100));
    MouseAndKeyEventUtil.keyEnter(KeyEvent.VK_ESCAPE);
  }

  /**
   * 处理图标
   */
  public static void handleIcon(GlobalConfigurationInfo configInfo, Robot robot, Point location) throws Exception {

    robot.delay(2000);
    String iconsPosition = configInfo.getMoveIconPosition();
    if (iconsPosition.contains(",")) {
      String[] positions = iconsPosition.split(",");
      for (int i = 0; i < positions.length; i++) {
        String[] iconPosition = positions[i].split("-");
        int x = (int) (Integer.parseInt(iconPosition[0]) + location.getX());
        int y = (int) (Integer.parseInt(iconPosition[1]) + location.getY());
        robot.mouseMove(x, y);
        robot.delay(DelayUtil.getMouseMoveDelayTime());
        robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
        MouseAndKeyEventUtil.moveMouse(new int[]{x, y}, new int[]{x, (int) (location.getY() + 20)}, MouseAndKeyEventUtil.STRAIGHT_LINE);
        robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
      }
    }
  }

  /**
   * 移动角色
   */
  public static void moveCharacterToDestinationByWestCoast(GlobalConfigurationInfo configInfo, Robot robot, Point location) throws Exception {

    MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);

    // TODO 角色进入液面时可能被其他的页面挡到了需要先按下 esc
    int[] position = getCharacterInitialPosition(configInfo, location);
    // colorRole
    Color roleColorNow = robot.getPixelColor(position[0], position[1]);

    while (!matchCharacter(roleColorNow, configInfo)) {
      MouseAndKeyEventUtil.keyEnter(KeyEvent.VK_ESCAPE);
    }

    // 移动到西海岸城镇门口
    robot.delay(DelayUtil.getStartRandomDelayTime()); // 角色在初始房间移动到右边
    robot.keyPress(KeyEvent.VK_RIGHT);
    robot.delay(4000);
    robot.keyRelease(KeyEvent.VK_RIGHT);

    // TODO 点击西海岸
    String[] westCoastPosition = configInfo.getWestCoastPosition().split("-");
    MouseAndKeyEventUtil.move(westCoastPosition, location);
    MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON1_DOWN_MASK);
    MouseAndKeyEventUtil.keyEnter(KeyEvent.VK_UP, 4000);
    int[] townDoorPosition = GetColorUtil.getPositionByColor(location, robot, PositionEnum.BOTTOM_RIGHT.getPosition(), ColorCodeLibraryEnum.TOWN_DOOR.getColor(), ColorCodeLibraryEnum.TOWN_DOOR.getValue());

    if (townDoorPosition != null) { // 没有进门
      // 获取门的颜色
      MouseAndKeyEventUtil.move(townDoorPosition);
      MouseAndKeyEventUtil.mouseEnter(InputEvent.BUTTON3_DOWN_MASK);
    }
  }

  private static int[] getCharacterInitialPosition(GlobalConfigurationInfo configInfo, Point location) {

    // TODO 需要自动识别
    String[] position = configInfo.getCharacterInitialPosition().split("-");
    int x = (int) (Integer.parseInt(position[0]) + location.getX());
    int y = (int) (Integer.parseInt(position[1]) + location.getY());

    return new int[]{x, y};
  }

  // 匹配角色色标
  private static boolean matchCharacter(Color roleColor, GlobalConfigurationInfo configInfo) {

    if (configInfo.getCurCharacter() == null) {
      CharacterEnum[] values = CharacterEnum.values();
      for (int i = 0; i < values.length; i++) {
        int[] colors = values[i].getColor();
        if (colors[0] == roleColor.getRed()
                && colors[1] == roleColor.getGreen()
                && colors[2] == roleColor.getBlue()) {

          if (configInfo.getCurCharacter() == null) {
            configInfo.setCurCharacter(values[i]);
          }
          return true;
        }
      }
    } else {
      int[] colors = configInfo.getCurCharacter().getColor();
      if (colors[0] == roleColor.getRed()
              && colors[1] == roleColor.getGreen()
              && colors[2] == roleColor.getBlue()) {

        return true;
      }
    }

    return false;
  }

  public static void moveCharacterToDuplicateDoor(TimerTaskFactory taskFactory,
                                                  Robot robot,
                                                  Rectangle rectangle,
                                                  GlobalConfigurationInfo configInfo,
                                                  final int[] characterPosition,
                                                  int[] duplicateDoorColors) throws Exception {

    int[] duplicateDoorPosition = PositionUtil.getPosition(robot, rectangle, duplicateDoorColors);

    CharacterEnum curCharacter = configInfo.getCurCharacter();
    int[] colors = curCharacter.getColor();
    boolean[] flag = {false, false};

    taskFactory.execute(() -> {
      final int[] bufInfo = {30, 120, 80, 130};
      int[] startInterval = {-1, -1}, position, finalRgb;
      int i, length;
      while (true) {
        long start = System.currentTimeMillis();
        startInterval[0] = characterPosition[0] - bufInfo[0];
        startInterval[1] = characterPosition[1] - bufInfo[1];
        rectangle.setBounds(startInterval[0], startInterval[1], bufInfo[2], bufInfo[3]);

        finalRgb = robot.createScreenCapture(rectangle)
                .getRGB(0, 0, bufInfo[2], bufInfo[3], null, 0, bufInfo[2]);
        length = finalRgb.length;
        for (i = 0; i < length; i += 20) {
          if (((finalRgb[i] >> 16) & 0xff) == colors[0]
                  && ((finalRgb[i] >> 8) & 0xff) == colors[1]
                  && (finalRgb[i] & 0xff) == colors[2]) {
            characterPosition[0] = (startInterval[0] + i % bufInfo[2]);
            characterPosition[1] = (startInterval[1] + i / bufInfo[2]) + 93;
            System.out.println(StringUtil.format("({}, {})", characterPosition[0], characterPosition[1]));
            break;
          }
        }

        if (i == finalRgb.length) {
          rectangle.setBounds((int) rectangle.getLocation().getX(), (int) rectangle.getLocation().getY(), 800, 600);
          position = PositionUtil.getPosition(robot, rectangle, curCharacter.getColor());
          characterPosition[0] = position[0];
          characterPosition[1] = position[1];
        }
        if (flag[0]) {
          break;
        }
        System.out.println(System.currentTimeMillis() - start);
      }
    });
    /*----------------  确定方向 ------------------*/
    // 横向
    int[] isRelease = {0, 0};
    int transverse = duplicateDoorPosition[0] - characterPosition[0];
    int direction = duplicateDoorPosition[1] - characterPosition[1];
    int[] keyboard = new int[2];

    if (transverse != 0) {
      keyboard[0] = (transverse > 0) ? KeyEvent.VK_RIGHT : KeyEvent.VK_LEFT;
      MouseAndKeyEventUtil.doubleClick(keyboard[0]);
      isRelease[0] = 1;
    }
    // 纵向
    if (direction != 0) {
      keyboard[1] = (direction > 0) ? KeyEvent.VK_DOWN : KeyEvent.VK_UP;
      MouseAndKeyEventUtil.doubleClick(keyboard[1]);
      isRelease[1] = 1;
    }
        /*while (true) {
            if (duplicateDoorPosition[0] != 0 && characterPosition[0] >= duplicateDoorPosition[0] - 15 && characterPosition[0] <= duplicateDoorPosition[0] + 15) {
                MouseAndKeyEventUtil.doubleClickRelease(robot, keyboard[0]);
                isRelease[0] = 0;
            }
            if (duplicateDoorPosition[1] != 0 && characterPosition[1] >= duplicateDoorPosition[1] - 15 && characterPosition[1] <= duplicateDoorPosition[1] + 15) {
                MouseAndKeyEventUtil.doubleClickRelease(robot, keyboard[1]);
                isRelease[1] = 0;
            }

            if (isRelease[0] == 0 && isRelease[1] == 0) {
                flag[0] = true;
                break;
            }
            robot.delay(5);
        }*/
  }


  public static void moveCharacterToPosition(TimerTaskFactory taskFactory,
                                             Robot robot,
                                             Rectangle rectangle,
                                             GlobalConfigurationInfo configInfo,
                                             final int[] characterPosition,
                                             int[] destPosition) {

    CharacterEnum curCharacter = configInfo.getCurCharacter();
    int[] colors = curCharacter.getColor();
    boolean[] flag = {false, false};

    taskFactory.execute(() -> {
            /*final int[] bufInfo = {30, 120, 80, 130};
            int[] startInterval = {-1, -1}, position, finalRgb;
            int i, length;*/
      System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
      Mat m1 = Imgcodecs.imread("C:\\Users\\Administrator\\Desktop\\TPlan\\TPlan\\src\\main\\resources\\images\\characters\\swordGod.jpg");
      Mat m2 = Imgcodecs.imread("C:\\Users\\Administrator\\Desktop\\TPlan\\TPlan\\src\\main\\resources\\images\\other\\door.jpg");
      double x, y, x1, y1;
      int row, col, rows = 800, cols = 600, i, m1X = m1.cols(), m1Y = m1.rows(), length;
      int[] key = {-1}, doorPosition = {-1, -1}, position = {0, 0};
      try {
        while (true) {
          long start = System.currentTimeMillis();
          CountDownLatch count = new CountDownLatch(1);
          ;
          Mat mat = OpenCvUtil.bufferedImageToMat(robot.createScreenCapture(rectangle));
          Mat res1 = new Mat(mat.rows(), mat.cols(), CvType.CV_32FC1);
                    /*Mat res2 = new Mat(mat.rows(), mat.cols(), CvType.CV_32FC1);

                    taskFactory.execute(() -> {
                        Imgproc.matchTemplate(mat, m2, res2, Imgproc.TM_CCORR);
                        Core.normalize(res2, res2,0, 1, Core.NORM_MINMAX, -1, new Mat());
                        count.countDown();
                    });*/

          taskFactory.execute(() -> {
            Imgproc.matchTemplate(mat, m1, res1, Imgproc.TM_CCORR);
            Core.normalize(res1, res1, 0, 1, Core.NORM_MINMAX, -1, new Mat());
            count.countDown();
          });

          count.await();

          Core.MinMaxLocResult min1 = Core.minMaxLoc(res1);
          position[0] = (int) min1.maxLoc.x + m1X;
          position[1] = (int) min1.maxLoc.y + m1Y;
          System.out.println(position[0] + "，" + position[1]);
                    /*rows = res2.rows();
                    cols = res2.cols();
                    length = rows * cols;
                    for (i = 0; i < length; i++) {
                        col = i / rows;
                        row = i % rows;
                        if (res2.get(row, col)[0] >= 0.99997) {
                            doorPosition[0] = col;
                            doorPosition[1] = row;
                            System.out.println(col + "，" + row);
                        }
                    }*/
//                    System.out.println(StringUtil.format("({},{}),({},{})", x, y, x1, y1));

                    /*startInterval[0] = characterPosition[0] - bufInfo[0];
                    startInterval[1] = characterPosition[1] - bufInfo[1];
                    rectangle.setBounds(startInterval[0], startInterval[1], bufInfo[2], bufInfo[3]);
                    finalRgb = robot.createScreenCapture(rectangle)
                            .getRGB(0, 0, bufInfo[2], bufInfo[3], null, 0, bufInfo[2]);
                    length = finalRgb.length;
                    for (i = 0; i < length; i += 20) {
                        if (((finalRgb[i] >> 16) & 0xff) == colors[0]
                                && ((finalRgb[i] >> 8) & 0xff) == colors[1]
                                && (finalRgb[i] & 0xff) == colors[2]) {
                            characterPosition[0] = (startInterval[0] + i % bufInfo[2]);
                            characterPosition[1] = (startInterval[1] + i / bufInfo[2]) + 93;
//                            System.out.println(StringUtil.format("({}, {})", characterPosition[0], characterPosition[1]));
                            break;
                        }
                    }

                    if (i == finalRgb.length) {
                        rectangle.setBounds((int) rectangle.getLocation().getX(), (int) rectangle.getLocation().getY(), 800, 600);
                        position = PositionUtil.getPosition(robot, rectangle, curCharacter.getColor());
                        characterPosition[0] = position[0];
                        characterPosition[1] = position[1];
                    }
                    if(flag[0]) {
                        break;
                    }*/
          System.out.println(System.currentTimeMillis() - start);
        }

      } catch (Exception e) {
        e.printStackTrace();
      }
    });

    /*----------------  确定方向 ------------------*//*
        // 横向
        int[] isRelease = {0, 0};
        int transverse = destPosition[0] - characterPosition[0];
        int direction = destPosition[1] - characterPosition[1];
        int[] keyboard = new int[2];

        if (transverse != 0) {
            keyboard[0] = (transverse > 0) ? KeyEvent.VK_RIGHT : KeyEvent.VK_LEFT;
            MouseAndKeyEventUtil.doubleClick(robot, keyboard[0]);
            isRelease[0] = 1;
        }
        // 纵向
        if (direction != 0) {
            keyboard[1] = (direction > 0) ? KeyEvent.VK_DOWN : KeyEvent.VK_UP;
            MouseAndKeyEventUtil.doubleClick(robot, keyboard[1]);
            isRelease[1] = 1;
        }
        while (true) {
            if (destPosition[0] != 0 && characterPosition[0] >= destPosition[0] - 15 && characterPosition[0] <= destPosition[0] + 15) {
                MouseAndKeyEventUtil.doubleClickRelease(robot, keyboard[0]);
                isRelease[0] = 0;
            }
            if (destPosition[1] != 0 && characterPosition[1] >= destPosition[1] - 15 && characterPosition[1] <= destPosition[1] + 15) {
                MouseAndKeyEventUtil.doubleClickRelease(robot, keyboard[1]);
                isRelease[1] = 0;
            }

            if (isRelease[0] == 0 && isRelease[1] == 0) {
                flag[0] = true;
                break;
            }
            robot.delay(5);
        }*/
  }

  // 根据方向获取
  public static int[] getCharacterPositionByKeyboard(TimerTaskFactory taskFactory, Robot robot, Point location, GlobalConfigurationInfo configInfo, int[] characterPosition, int[] keyboardPosition) {

    long start = System.currentTimeMillis();
    CharacterEnum curCharacter = configInfo.getCurCharacter();
//        int interval = curCharacter.getInterval() / 2;
    int intervalX = 23;
    int intervalY = 14;
    int[] roleColor = curCharacter.getColor();
    int x = -1, y = -1;
    if (keyboardPosition[0] == KeyEvent.VK_RIGHT) {
      if (keyboardPosition[1] == -1) {
        int endX = (int) (location.getX() + Integer.parseInt(configInfo.getWindowInfo().split("-")[0]));
        for (x = characterPosition[0] + intervalX, y = characterPosition[1]; x <= endX; x += intervalX) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break;
          }
        }
      } else if (keyboardPosition[1] == KeyEvent.VK_UP) {
        int endX = (int) (location.getX() + Integer.parseInt(configInfo.getWindowInfo().split("-")[0]));
        for (x = characterPosition[0] + intervalX, y = characterPosition[1] - intervalY; x <= endX; x += intervalX, y -= intervalY) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break; //23 - 14
          }
        }
      } else if (keyboardPosition[1] == KeyEvent.VK_DOWN) {
        int endX = (int) (location.getX() + Integer.parseInt(configInfo.getWindowInfo().split("-")[0]));
        for (x = characterPosition[0] + intervalX, y = characterPosition[1] + intervalY; x <= endX; x += intervalX, y += intervalY) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break;
          }
        }
      }
    } else if (keyboardPosition[0] == KeyEvent.VK_LEFT) {
      if (keyboardPosition[1] == -1) {
        int endX = (int) location.getX();
        for (x = characterPosition[0] - intervalX, y = characterPosition[1]; x >= endX; x -= intervalX) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            y = characterPosition[1];
            break;
          }
        }
      } else if (keyboardPosition[1] == KeyEvent.VK_UP) {
        int endX = (int) (location.getX() + Integer.parseInt(configInfo.getWindowInfo().split("-")[0]));
        for (x = characterPosition[0] - intervalX, y = characterPosition[1] - intervalY; x >= endX; x -= intervalX, y -= intervalY) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break;
          }
        }
      } else if (keyboardPosition[1] == KeyEvent.VK_DOWN) {
        int endX = (int) (location.getX() + Integer.parseInt(configInfo.getWindowInfo().split("-")[0]));
        for (x = characterPosition[0] - intervalX, y = characterPosition[1] + intervalY; x >= endX; x -= intervalX, y += intervalY) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break;
          }
        }
      }
    } else if (keyboardPosition[0] == -1) {
      if (keyboardPosition[1] == KeyEvent.VK_UP) {
        int endY = (int) location.getY();
        for (x = characterPosition[0], y = characterPosition[1] - intervalY; y >= endY; y -= intervalY) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break;
          }
        }
      } else if (keyboardPosition[1] == KeyEvent.VK_DOWN) {
        int endY = (int) location.getY();
        for (x = characterPosition[0], y = characterPosition[1] + intervalY; y <= endY; y += intervalY) {
          Color pixelColor = robot.getPixelColor(x, y);
          if (roleColor[0] == pixelColor.getRed()
                  && roleColor[1] == pixelColor.getGreen()
                  && roleColor[2] == pixelColor.getBlue()) {
            break;
          }
        }
      }
    }
    System.out.println("time => " + (System.currentTimeMillis() - start) + "(" + x + ", " + y + ")");
    return null;
//        return PositionUtil.computeCharacterPosition(robot, taskFactory, x, y, configInfo.getCurCharacter());
  }

  public static void mobileCharacter(int[] positions, int[] destPosition, int[] keycodes) throws Exception {
    if (positions[0] - destPosition[0] >= 0) {
      keycodes[0] = KeyEvent.VK_LEFT;
    } else {
      keycodes[0] = KeyEvent.VK_RIGHT;
    }

    if (positions[1] - destPosition[1] >= 0) {
      keycodes[1] = KeyEvent.VK_UP;
    } else {
      keycodes[1] = KeyEvent.VK_DOWN;
    }
    int abs = Math.abs(positions[0] -  destPosition[0]);
    if (abs >= 180) {
      MouseAndKeyEventUtil.doubleClick(keycodes[0]);
    } else {
      MouseAndKeyEventUtil.keyPress(keycodes[0]);
    }
    MouseAndKeyEventUtil.keyPress(keycodes[1]);
  }

  public static boolean confirmWhetherMove(int[] counts, int[] pro, int[] positions) {
    int xAbs1 = Math.abs(positions[0] - 337);
    int xAbs2 = Math.abs(positions[0] - 340);
    int xAbs3 = Math.abs(positions[0] - 441);
    int xAbs4 = Math.abs(positions[0] - 438);
    // 438 441 340 337
    if (!(xAbs1 < 1 || xAbs2 < 1 || xAbs3 < 1 || xAbs4 < 1) && pro[0] == positions[0] && pro[1] == positions[1]) {
      if (++counts[1] > 5) {
        counts[1] = 0;
        return false;
      }
    } else {
      counts[1] = 0;
    }

    pro[0] = positions[0];
    pro[1] = positions[1];
    return true;
  }
}